<template>
  <div class="l-flex--col" v-if="isShow">
    <div
      style="margin-bottom: 10px"
      v-if="quickCheck && !isDetail && quickMap.length"
    >
      维保项目快选：
      <el-checkbox
        :value="isCheck(item)"
        @change="quickCheckChange(item, $event)"
        v-for="(item, index) in quickMap"
        :key="index"
      >
        {{ item }}
      </el-checkbox>
    </div>
    <div class="inspection">
      <div
        class="inspection-item"
        v-for="(title, level) in titles"
        :key="level"
      >
        <div class="title-wrapper">
          <div class="item-title">{{ title }}</div>
        </div>
        <div
          class="list-wrapper"
          v-if="getLevelListData(level) && getLevelListData(level).length"
        >
          <template v-for="(item, index) in getLevelListData(level)">
            <div
              class="list-item l-flex--row u-pointer"
              @click="setActive(level, index)"
              :key="index"
              :class="
                index === levelStatus[level].index ? 'active' : 'inactive'
              "
            >
              <el-checkbox
                v-if="!isDetail"
                :indeterminate="item.$isIndeterminate"
                :value="item.$checked"
                @change="handleCheckAllChange(item, $event)"
                style="margin-right: 2em"
              ></el-checkbox>
              <div class="l-flex__fill l-flex--col">
                <div v-if="!isDetail">
                  {{ item.name
                  }}{{ item.categorySuffix ? `(${item.categorySuffix})` : '' }}
                </div>
                <template v-if="isDetail">
                  <template v-if="type == 'wb'">
                    <div class="l-flex--row" :class="{ pt: item.detailShow }">
                      <div class="l-flex__fill">
                        {{ item.name
                        }}{{
                          item.categorySuffix ? `(${item.categorySuffix})` : ''
                        }}
                      </div>
                      <div
                        v-if="
                          (!item.children || item.children.length == 0) &&
                          !hideDetail
                        "
                        class="btn"
                        @click="showDetail(item)"
                        :style="{
                          color: [0, 1, 2].includes(item.status)
                            ? '#000'
                            : '#0D48CE',
                          cursor: [0, 1, 2].includes(item.status)
                            ? 'unset'
                            : 'pointer',
                          marginRight: '10px'
                        }"
                      >
                        {{
                          ['正常', '已维护', '忽略/无此项', '需维修', '需大修'][
                            item.status
                          ]
                        }}
                      </div>
                    </div>
                    <div
                      class="detail wb"
                      v-show="
                        ![0, 1, 2].includes(item.status) && item.detailShow
                      "
                    >
                      <template v-if="item.photo">
                        <CImgUploadNew
                          editMode="detail"
                          class="imgListUpload"
                          :initList="
                            item.photo
                              ? item.photo
                                  .split(',')
                                  .filter(i => i)
                                  .map(i => ({ fileUrl: i }))
                              : []
                          "
                          actionUrl=""
                          :uploadParas="{ type: 'image', fileNum: 999 }"
                        ></CImgUploadNew>
                      </template>
                      <el-empty v-else></el-empty>
                    </div>
                  </template>
                  <template v-else>
                    <div class="l-flex--row" :class="{ pt: item.detailShow }">
                      <div class="l-flex__fill">{{ item.name }}</div>
                      <div
                        v-if="item.children && item.children.length == 0"
                        class="btn"
                        @click="showDetail(item)"
                        :style="{
                          color: item.result == 2 ? '#0D48CE' : '#000',
                          cursor: item.result == 2 ? 'pointer' : 'unset',
                          marginRight: '10px'
                        }"
                      >
                        {{
                          item.result == 1
                            ? '合格'
                            : item.result == 2
                            ? '不合格'
                            : '未检查'
                        }}
                      </div>
                    </div>
                    <div
                      class="detail"
                      v-show="item.result == 2 && item.detailShow"
                    >
                      <div class="tip">{{ item.description }}</div>
                      <CImgUploadNew
                        editMode="detail"
                        class="imgListUpload"
                        :initList="
                          item.picUrl
                            ? item.picUrl
                                .filter(i => i)
                                .map(i => ({ fileUrl: i }))
                            : []
                        "
                        actionUrl=""
                        :uploadParas="{ type: 'image', fileNum: 999 }"
                      ></CImgUploadNew>
                    </div>
                  </template>
                </template>
              </div>
            </div>
          </template>
        </div>
        <el-empty
          v-else
          :image="require('@/assets/emptyBackGround.png')"
          description="暂无数据"
          :image-size="200"
        ></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import { deepClone } from '@/utils/index';
import CImgUploadNew from '@/components/Upload/CImgUploadNew';
import { detailRecord } from '@/api/elevator-dailyCheck/checkRecord/index';
export default {
  name: 'inspection',
  props: {
    titleMap: {
      type: Array,
      default: () => ['一级巡检项目', '二级巡检项目', '三级巡检项目']
    },
    checkMap: {
      type: Array,
      default: () => []
    },
    quickCheck: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'xj'
    },
    hideDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    CImgUploadNew
  },
  data() {
    return {
      levelStatus: [
        {
          index: 0,
          clicked: false
        },
        {
          index: 0,
          clicked: false
        },
        {
          index: 0,
          clicked: false
        }
      ],
      dataMap: {},
      data: [],
      isDetail: false,
      checked1: [],
      checked2: [],
      checked3: [],
      quickMap: [],
      isShow: false,
      list: []
    };
  },
  computed: {
    titles() {
      return this.titleMap;
    }
  },
  // watch: {
  //   list: {
  //     handler(val) {
  //       if (!val.length) return;
  //       this.initCheckData(val);
  //     }
  //     // immediate: true
  //   }
  // },
  created() {
    for (let i = 0; i < this.titles.length; i++) {
      this.getLevelListData(i);
    }
  },
  methods: {
    isCheck(cat) {
      let flag = false;
      for (const key in this.dataMap) {
        if (Object.hasOwnProperty.call(this.dataMap, key)) {
          const item = this.dataMap[key];
          if (this.hasChildren(item)) {
            continue;
          }
          if (
            item.categorySuffix &&
            item.categorySuffix.split('.').includes(cat)
          ) {
            if (item.$isIndeterminate || item.$checked) {
              flag = true;
            } else {
              return false;
            }
          }
        }
      }
      return flag;
    },
    quickCheckChange(cat, visible) {
      let flag = false;
      for (const key in this.dataMap) {
        if (Object.hasOwnProperty.call(this.dataMap, key)) {
          const item = this.dataMap[key];
          if (this.hasChildren(item)) {
            continue;
          }
          if (
            item.categorySuffix &&
            item.categorySuffix.split('.').includes(cat)
          ) {
            if (visible) {
              item.$isIndeterminate = false;
              item.$checked = true;
            } else {
              item.$isIndeterminate = false;
              item.$checked = false;
            }
            flag = true;
            this.handleCheckAllChange(item, visible);
          }
        }
      }
      if (!flag) {
        this.$message.error(`没有${cat}项`);
        return;
      }
    },
    handleSubmitData() {
      const checked1 = [];
      const checked2 = [];
      const checked3 = [];
      for (const key in this.dataMap) {
        if (Object.hasOwnProperty.call(this.dataMap, key)) {
          const item = this.dataMap[key];
          if (item.$isIndeterminate || item.$checked) {
            const map = {
              1: checked1,
              2: checked2,
              3: checked3
            };
            map[item.level].push(item);
          }
        }
      }
      this.checked1 = checked1;
      this.checked2 = checked2;
      this.checked3 = checked3;
    },
    show(val) {
      this.isDetail = val == 'detail';
      this.initTree();
      this.initCheckData(this.list);
      this.isShow = true;
    },
    initTree() {
      if (this.isDetail) {
        this.list = this.toTree(deepClone(this.data));
      } else {
        this.list = deepClone(this.data);
      }
    },
    getItem(id) {
      return this.dataMap[id];
    },
    checkAll(node, value) {
      //处理子节点
      if (!this.hasChildren(node)) return;
      node.children.forEach(n => {
        n.$checked = value;
        n.$isIndeterminate = false;
        this.checkAll(n, value);
      });
    },
    checkIndeterminate(node) {
      //处理父
      if (!node) return;
      let root = node;
      // 向上遍历父级节点
      while (root) {
        if (this.hasChildren(root)) {
          // 获取当前循环节点已选择的子节点个数
          const checkedChildNodes = root.children.filter(item => item.$checked);

          // 如果没有一个子节点被选中，那么当前节点为不勾选
          if (checkedChildNodes.length === 0) {
            root.$checked = false;
            root.$isIndeterminate = false;
          } else if (checkedChildNodes.length < root.children.length) {
            // 如果有未勾选的子节点，退出循环，因为从该节点开始以及该节点的所有父级节点都是半状态
            break;
          } else {
            // 到这里说明所有子节点都是选中状态，设置该节点为选中
            root.$isIndeterminate = false;
            root.$checked = true;
          }
        }
        root = this.getItem(root.parentId);
      }

      // 如果 root 不为空，将该节点以及该节点的所有父级节点设置为半选状态
      while (root) {
        root.$checked = false;
        root.$isIndeterminate = true;
        root = this.getItem(root.parentId);
      }
      return root;
    },
    handleCheckAllChange(node, value) {
      node.$checked = node.$isIndeterminate ? true : value;
      if (node.$isIndeterminate) {
        node.$isIndeterminate = false;
      }

      this.checkAll(node, node.$checked);
      this.checkIndeterminate(this.getItem(node.parentId));
      this.handleSubmitData();
    },
    isSelected(data) {
      if (this.checkMap.length) {
        return this.checkMap.includes(data.id);
      } else {
        return !!data.selected;
      }
    },
    hasChildren(node) {
      if (!node.children) return false;
      return !!node.children.length;
    },
    dfs(node) {
      if (node === null) return;
      this.dataMap[node.id] = node;
      node.parentId = node.parentId || node.pid;
      this.$set(node, '$checked', this.isSelected(node));
      this.$set(node, '$isIndeterminate', false);
      if (this.hasChildren(node)) {
        if (!this.isDetail) {
          const checkedChildNodes = node.children.filter(item =>
            this.isSelected(item)
          );
          if (checkedChildNodes.length === 0) {
            this.$set(node, '$checked', false);
            this.$set(node, '$isIndeterminate', false);
          } else if (checkedChildNodes.length < node.children.length) {
            this.$set(node, '$checked', false);
            this.$set(node, '$isIndeterminate', true);
          } else {
            this.$set(node, '$checked', true);
            this.$set(node, '$isIndeterminate', false);
          }
        }
        for (let child of node.children) {
          this.dfs(child);
        }
      } else {
        if (this.quickCheck && !this.isDetail) {
          if (node.categorySuffix) {
            for (const item of node.categorySuffix.split('.')) {
              if (!this.quickMap.includes(item)) {
                this.quickMap.push(item);
              }
            }
          }
        }
      }
    },
    toTree(list) {
      const res = [];
      const map = list.reduce((res, v) => ((res[v.id] = v), res), {});
      for (const item of list) {
        if (!item.parentId) {
          res.push(item);
          continue;
        }
        if (item.parentId in map) {
          const parent = map[item.parentId];
          parent.children = parent.children || [];
          parent.children.push(item);
        }
      }
      return res;
    },
    initCheckData(data) {
      if (this.isDetail) {
        return;
      }
      for (const item of data) {
        this.dfs(item);
      }
      this.handleSubmitData();
      this.sortQuickMap();
    },
    sortQuickMap() {
      if (this.quickCheck) {
        // 提取数字部分和字母部分
        this.quickMap.sort((a, b) => {
          // 将字符串转换为数字，如果无法转换则返回0
          const numA = Number(a[1]) || 0;
          const numB = Number(b[1]) || 0;

          // 首先按字母表顺序比较字母部分
          const letterCompare = a[0].localeCompare(b[0]);

          // 如果字母部分相同，则按数字部分升序排序
          if (letterCompare === 0) {
            return numA - numB;
          } else {
            return letterCompare;
          }
        });
      }
    },
    resetLevelStatus(level) {
      for (let i = 0; i < this.levelStatus.length; i++) {
        if (i >= level) {
          // 只把当前点击的层级和子集置为0，上级不能置0，否则选项就变成了其他项目
          this.$set(this.levelStatus[i], 'index', 0);
        }

        this.$set(this.levelStatus[i], 'clicked', false);
      }
    },
    setActive(level, index) {
      this.resetLevelStatus(level);
      this.$set(this.levelStatus[level], 'index', index);
      this.$set(this.levelStatus[level], 'clicked', true);
    },
    getLevelListData(level) {
      if (level === 0) {
        return this.list.filter(item => item.level === 1);
      } else if (level === 1) {
        let parent = this.list[this.levelStatus[level - 1].index];

        if (parent && parent.children) {
          return parent.children;
        }
      } else if (level === 2) {
        let lvl0 = this.list[this.levelStatus[0].index];
        let lvl1 = [];
        let lvl2 = [];

        if (lvl0 && lvl0.children) {
          lvl1 = lvl0.children[this.levelStatus[1].index];

          if (lvl1 && lvl1.children) {
            lvl2 = lvl1.children;

            return lvl2;
          } else {
            return [];
          }
        } else {
          return [];
        }
      }
    },
    // 0正常，1已维护，2忽略/无此项，3需维修，4需大修
    showDetail(option) {
      if (this.type == 'wb') {
        if ([0, 1, 2].includes(option.status)) return false;
      } else {
        if (option.result != 2) return false;
      }
      this.$set(option, 'detailShow', !option.detailShow);
      if (option.detailShow) {
        if (this.type == 'xj') {
          detailRecord(option.taskRecordId)
            .then(result => {
              option.picUrl = result.data.picUrl;
              option.description = result.data.description;
            })
            .catch(err => {});
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.inspection {
  display: flex;
  flex-direction: row;
  flex: 1;
  height: 100%;
}
.inspection-item {
  background: #fff;
  flex: 1;
  margin: 5px;
  border-radius: 10px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  height: 100%;

  .title-wrapper {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 14px;

    .item-title {
      text-align: center;
      color: #3d3d3d;
      font-size: 16px;
      font-weight: bold;
      line-height: 22px;
    }

    .title-btn {
      font-size: 14px;
    }
  }

  .list-wrapper {
    overflow-y: auto;

    .list-item {
      background: #f6f6f6;
      min-height: 38px;
      border-radius: 4px;
      padding: 10px 12px;
      color: #3d3d3d;
      line-height: 28px;
      font-size: 14px;
      margin: 5px 0;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }

    .list-item.active {
      background: #fff;
      border: 1px solid #0d48ce;
      color: #0d48ce;
    }

    .list-item.active:hover {
      background: rgba(13, 72, 206, 0.1);
    }

    .list-item.inactive {
      background: #f6f6f6;
      border: none;
      color: #3d3d3d;
    }

    .btn-group {
      width: 54px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }

    .btn-group span {
      display: inline-block;
      width: 14px;
      height: 14px;
      background-position: center;
    }

    .btn-view {
      background: url('~@/assets/widget/small-view-btn.svg') no-repeat;
    }

    .btn-edit {
      background: url('~@/assets/widget/small-edit-btn.svg') no-repeat;
    }

    .btn-delete {
      background: url('~@/assets/widget/small-delete-btn.svg') no-repeat;
    }
  }
}

.list-wrapper {
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 4px;
  }

  &::-webkit-scrollbar-track-piece {
    background: rgba(200, 200, 200, 0.1);
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    background: rgba(200, 200, 200, 0.5);
  }
}
.detail {
  margin-top: 1em;
  ::v-deep .upload-con {
    border: none;
    padding: 12px;
    min-height: auto;
    background: transparent;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;
  }
}
.tip {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.5);
  line-height: 20px;
  padding-left: 5px;
}
.imgListUpload {
  gap: 0 10px;
  // min-height: unset;
}
::v-deep .el-empty {
  padding: 0;
}
.pt {
  padding-top: 12px;
}
</style>
